package com.example.dllo.my36kr.news;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dllo.my36kr.R;
import com.example.dllo.my36kr.loading.MySwipeRefreshLayout;
import com.example.dllo.my36kr.main.MainActivity;
import com.example.dllo.my36kr.news.newsecond.SecondActivity;
import com.example.dllo.my36kr.news.project.ProjectAdapter;
import com.example.dllo.my36kr.news.project.ProjectBean;
import com.example.dllo.my36kr.news.video.VideoAdapter;
import com.example.dllo.my36kr.news.video.VideoBean;
import com.example.dllo.my36kr.search.SearchActivity;
import com.example.dllo.my36kr.tools.BaseFragment;
import com.example.dllo.my36kr.tools.MyApp;
import com.example.dllo.my36kr.tools.NetTool;
import com.example.dllo.my36kr.tools.StaticUrl;

import java.util.ArrayList;


/**
 * Created by dllo on 16/8/15.
 */

/**
 * 新闻
 */
public class NewsFragment extends BaseFragment implements View.OnClickListener {
    private ListView listView;
    private NewsAdapter adapter;//新闻
    private ViewPager viewPager;//新闻 轮播图
    private NewsViewPager pager;//轮播图 适配器
    private ArrayList<String> arrayList;//轮播图 集合
    private View view;//轮播图 的视图
    private BatteryReceiver mReceiver;//抽屉 listView 的广播接收器
    private ProjectAdapter projectAdapter;//抽屉 点击解析的adapter
    Handler handler = new Handler(new Handler.Callback() {//轮播图 线程
        @Override
        public boolean handleMessage(Message msg) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            //obtainMessage 和new Message 一样
            //只是能节省一些内存
            Message message = handler.obtainMessage();
            message.what = 1;
            //可以让msg在延迟多少毫秒好 才被handler 的callbacck执行
            handler.sendMessageDelayed(message, 5000);
            return false;
        }
    });
    private TextView newsTv;
    private boolean head = false;

    private String all;
    private VideoAdapter videoAdapter;
    private MySwipeRefreshLayout layout;
    int page = 1;
    boolean a = false;
    private int w;


    @Override
    protected int setLayout() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initView() {
        newsTv = bindView(R.id.tv_news_xinwen);
        //早期项目
        projectAdapter = new ProjectAdapter(getContext());

        videoAdapter = new VideoAdapter(getContext());

        //加载
        layout = bindView(R.id.mysr_news_jiazai);
        listView = bindView(R.id.lv_news);
        adapter = new NewsAdapter(MyApp.getContext());
        /** listView.addHeaderView(view);*/

        view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_news_lunbotu, null);
        viewPager = bindView(view, R.id.vp_main_lunbotu);

        pager = new NewsViewPager(MyApp.getContext());
        Button drawerBnt = bindView(R.id.bnt_news_chouti);//按钮 抽屉
        drawerBnt.setOnClickListener(this);
        Button searchBnt = bindView(R.id.bnt_news_sousuo);
        searchBnt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), SearchActivity.class));
            }
        });

    }

    @Override
    public void onStart() {
        super.onStart();


        Message message = handler.obtainMessage();//线程
        message.what = 1;
        handler.sendMessageDelayed(message, 5000);
        mReceiver = new BatteryReceiver();//广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("a");
        filter.addAction("b");
        filter.addAction("c");
        getContext().registerReceiver(mReceiver, filter);

    }

    @Override
    public void onStop() {
        super.onStop();
        handler.removeMessages(1);//停止线程
        getContext().unregisterReceiver(mReceiver);//关闭广播

    }

    @Override
    protected void initData() {
        record();

        layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {//下拉刷新
            @Override
            public void onRefresh() {//下拉刷新
                listView.setAdapter(null);
                listView.removeHeaderView(view);
                record();
                layout.setRefreshing(false);

            }
        });

        layout.setOnLoadListener(new MySwipeRefreshLayout.OnLoadListener() {//上拉加载
            @Override
            public void onLoad() {
                page++;
                mNetTool.getNetData("https://rong.36kr.com/api/mobi/news?pageSize=" + (page * 20) + "&columnId=all&pagingAction=up", NewsBean.class, new NetTool.NetListener<NewsBean>() {
                    @Override
                    public void onSuccess(final NewsBean newsBean) {
                        adapter.setNewsBean(newsBean);
                        layout.setLoading(false);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(getActivity(), SecondActivity.class);
                                intent.putExtra("details", newsBean.getData().getData().get(position - 1).getFeedId());
                                startActivity(intent);

                            }
                        });
                    }
                    @Override
                    public void onError(String errorMsg) {

                    }
                });

            }
        });

    }

    public void record() {
        arrayList = new ArrayList<>();
        mNetTool.getNetData(StaticUrl.NEWS_DATA_URL, NewsBean.class, new NetTool.NetListener<NewsBean>() {
            @Override
            public void onSuccess(final NewsBean newsBean) {
                adapter.setNewsBean(newsBean);
                listView.setAdapter(adapter);
                /**        */
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(getActivity(), SecondActivity.class);
                        intent.putExtra("details", newsBean.getData().getData().get(position - 1).getFeedId());
                        startActivity(intent);

                    }
                });

            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_SHORT).show();
            }
        });

        mNetTool.getNetData(StaticUrl.NEWS_LUNBOTU_URL, NewsPicBean.class, new NetTool.NetListener<NewsPicBean>() {
            @Override
            public void onSuccess(NewsPicBean newsPicBean) {
                for (int i = 0; i < newsPicBean.getData().getPics().size(); i++) {
                    arrayList.add(newsPicBean.getData().getPics().get(i).getImgUrl());
                }
                pager.setmList(arrayList);
                pager.setViewPager(viewPager);
                viewPager.setAdapter(pager);
                listView.addHeaderView(view);
            }
            @Override
            public void onError(String errorMsg) {
                Toast.makeText(mContext, "图片请求失败", Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    public void onClick(View v) {

        MainActivity mainActivity = (MainActivity) getActivity();//点击 抽屉
        mainActivity.openMenu();
    }

    private class BatteryReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, final Intent intent) {

            all = intent.getStringExtra("all");
            String action = intent.getAction();


            switch (action) {
                case "b":
                    if (head == true) {
                        initData();
                        head = false;
                    }
                    break;
                case "a":
                    w = 1;
                    mNetTool.getNetData("https://rong.36kr.com/api/mobi/news?pageSize=20&columnId=" + all + "&pagingAction=up", ProjectBean.class, new NetTool.NetListener<ProjectBean>() {
                        @Override
                        public void onSuccess(final ProjectBean projectBean) {
                            projectAdapter.setList(projectBean);
                            listView.setAdapter(projectAdapter);
                            listView.removeHeaderView(view);
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Intent intent = new Intent(getActivity(), SecondActivity.class);
                                    intent.putExtra("details", projectBean.getData().getData().get(position).getFeedId());
                                    startActivity(intent);

                                }
                            });
                            head = true;
                        }

                        @Override
                        public void onError(String errorMsg) {
                        }
                    });
                    allA(all);


                    break;
                case "c":
                    mNetTool.getNetData(all, VideoBean.class, new NetTool.NetListener<VideoBean>() {
                        @Override
                        public void onSuccess(VideoBean videoBean) {
                            videoAdapter.setVideoBean(videoBean);
                            listView.setAdapter(videoAdapter);
                            listView.removeHeaderView(view);
                            head = true;
                        }

                        @Override
                        public void onError(String errorMsg) {

                        }
                    });
                    break;
            }
            if (all.equals(StaticUrl.NEWS_DATA_URL)) {
                newsTv.setText("全部");
            } else if (all.equals("67")) {
                newsTv.setText("早期项目");
            } else if (all.equals("68")) {
                newsTv.setText("B轮后");
            } else if (all.equals("23")) {
                newsTv.setText("大公司");
            } else if (all.equals("69")) {
                newsTv.setText("资本");
            } else if (all.equals("70")) {
                newsTv.setText("深度");
            } else if (all.equals("71")) {
                newsTv.setText("研究");
            } else {
                newsTv.setText("氪KV");
            }

        }

    }

    public void allA(final String s) {

        layout.setOnLoadListener(new MySwipeRefreshLayout.OnLoadListener() {//上拉加载
            @Override
            public void onLoad() {
                w++;
                mNetTool.getNetData("https://rong.36kr.com/api/mobi/news?pageSize=" + (w * 20) + "&columnId=" + s + "&pagingAction=up", ProjectBean.class, new NetTool.NetListener<ProjectBean>() {
                    @Override
                    public void onSuccess(final ProjectBean projectBean) {
                        projectAdapter.setList(projectBean);
                        listView.setAdapter(projectAdapter);
                        listView.removeHeaderView(view);
                        layout.setLoading(false);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(getActivity(), SecondActivity.class);
                                intent.putExtra("details", projectBean.getData().getData().get(position).getFeedId());
                                startActivity(intent);
                            }
                        });
                        head = true;
                    }

                    @Override
                    public void onError(String errorMsg) {

                    }
                });

            }
        });
        layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {//下拉刷新
            @Override
            public void onRefresh() {//下拉刷新
                listView.setAdapter(null);
                listView.removeHeaderView(view);
                layout.setRefreshing(false);
                mNetTool.getNetData("https://rong.36kr.com/api/mobi/news?pageSize=20&columnId=" + s + "&pagingAction=up", ProjectBean.class, new NetTool.NetListener<ProjectBean>() {
                    @Override
                    public void onSuccess(final ProjectBean projectBean) {
                        projectAdapter.setList(projectBean);
                        listView.setAdapter(projectAdapter);
                        listView.removeHeaderView(view);
                        layout.setLoading(false);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(getActivity(), SecondActivity.class);
                                intent.putExtra("details", projectBean.getData().getData().get(position).getFeedId());
                                startActivity(intent);

                            }
                        });
                        head = true;
                    }

                    @Override
                    public void onError(String errorMsg) {
                    }
                });

            }
        });

    }

}







